/*
 * Copyright @ 2018 河南雪城软件有限公司  All rights reserved.
 *
 */

package com.hw.one.peach.da.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hw.one.client.Client;
import com.hw.one.component.data.transform.excel.Export;
import com.hw.one.core.controller.BaseController;
import com.hw.one.core.logger.annotation.SystemLog;
import com.hw.one.core.logger.constant.LogConstants;
import com.hw.one.core.result.MsgResult;
import com.hw.one.peach.da.mongo.IVOCsMongo;
import com.hw.one.peach.da.service.IPeachDeviceService;
import com.hw.one.peach.da.service.IVOCsService;
import com.hw.one.unifiedcode.po.UnifiedCodePo;
import com.hw.one.unifiedcode.service.IUnifiedcodeService;

import io.swagger.annotations.ApiOperation;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

/**
 * <p>
 * 详细描述
 * </p>
 *
 * @author Erick
 * @date 2018/06/27
 */
@RestController
@RequestMapping("voc")
public class VOCController extends BaseController {

	@Resource
	private IPeachDeviceService peachDeviceService;
	
	@Resource
	private IUnifiedcodeService unifiedcodeService;
	
	/**
	 * voc原始数据查询
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "VOC数据接口", notes = "VOC数据接口原始数据查询", httpMethod = "GET")
	@SystemLog(moduleName = "VOC数据接口", description = "VOC数据接口原始数据查询", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "original-data", method = RequestMethod.GET)
	public MsgResult findAirOriginalData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'VOCS'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("voc-original-data", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("voc原始数据查询异常", e);
		}
		return result;
	}

	/**
	 * voc原始数据查询
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "VOC数据接口", notes = "VOC数据接口原始数据导出", httpMethod = "GET")
	@SystemLog(moduleName = "VOC数据接口", description = "VOC数据接口原始数据导出", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "original-data-export", method = RequestMethod.GET)
	public void exportVOCOriginalData(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> params = wrapParams(request);
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'VOCS'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = null;
			String ret = null;
			MsgResult obj = null;
			Gson gson = new Gson();
			JSONObject o = null;
			// 三大类数据
			c = Client.getInstance();
			params.put("type", "category");
			ret = c.execute("voc-original-data", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);
			obj = JSON.parseObject(ret, MsgResult.class);
			o = (JSONObject) JSON.toJSON(obj.getData());
			List<Map<String,String>> categoryList = gson.fromJson(o.get("rows").toString(), new TypeToken<List<HashMap<String, String>>>() {}.getType());
			
			// 十四小类数据
			c = Client.getInstance();
			params.put("type", "class");
			ret = c.execute("voc-original-data", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);
			obj = JSON.parseObject(ret, MsgResult.class);
			o = (JSONObject) JSON.toJSON(obj.getData());
			List<Map<String,String>> classList = gson.fromJson(o.get("rows").toString(), new TypeToken<List<HashMap<String, String>>>() {}.getType());
			
			// 组分数据
			c = Client.getInstance();
			params.put("type", "component");
			ret = c.execute("voc-original-data", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);
			obj = JSON.parseObject(ret, MsgResult.class);
			o = (JSONObject) JSON.toJSON(obj.getData());
			List<Map<String,String>> componentList = gson.fromJson(o.get("rows").toString(), new TypeToken<List<HashMap<String, String>>>() {}.getType());
			
			Map<String, Object> sheet = new LinkedHashMap<String, Object>();
			sheet.put("三大类", new HashMap<String, Object>(){{put("voc", categoryList);}});
			sheet.put("十四小类", new HashMap<String, Object>(){{put("voc", classList);}});
			sheet.put("VOCS组分", new HashMap<String, Object>(){{put("voc", componentList);}});
			
			System.setProperty("org.apache.poi.util.POILogger", "org.apache.poi.util.CommonsLogger");
			
			Export export = new Export();
			
			InputStream xml = this.getClass().getClassLoader().getResourceAsStream("/ext/tpl/excel/da/tpl-voc-hour-export.xml");
			Workbook workbook = export.exportExcelFromData(xml, sheet);
			
			response.setHeader("Content-Disposition", "attachment;filename=" + new String("voc原始数据.xlsx".getBytes("UTF-8"), "ISO-8859-1"));
			response.setContentType("multipart/form-data");
			
//			OutputStream os = new java.io.FileOutputStream(new File("E:\\voc.xlsx"));
			OutputStream os = response.getOutputStream();
			workbook.write(os);
			workbook.close();
			os.flush();
			os.close();
		} catch (Exception e) {
			log.error("voc原始数据查询异常", e);
		}
	}
	
	/**
	 * 获取voc的分类统计数据
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "VOC数据接口", notes = "VOC数据接口分类统计数据", httpMethod = "POST")
	@SystemLog(moduleName = "VOC数据接口", description = "VOC数据接口分类统计数据", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "component-data", method = RequestMethod.POST)
	public MsgResult findVocComponentData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'VOCS'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));
			
			Client c = Client.getInstance();
			String ret = c.execute("voc-component-data", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.POST);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("获取voc的分类统计数据异常", e);
		}
		return result;
	}

	/**
	 * 获取voc的均值统计数据
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "VOC数据接口", notes = "VOC数据接口均值统计数据", httpMethod = "POST")
	@SystemLog(moduleName = "VOC数据接口", description = "VOC数据接口均值统计数据", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "average-data", method = RequestMethod.POST)
	public MsgResult findVocAverageData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'VOCS'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("voc-average-data", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.POST);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("获取voc的均值统计数据异常", e);
		}
		return result;
	}

	/**
	 * 获取voc组分前十条数据
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "VOC数据接口", notes = "VOC数据接口获取组分前十条数据", httpMethod = "GET")
	@SystemLog(moduleName = "VOC数据接口", description = "VOC数据接口获取组分前十条数据", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "top-component", method = RequestMethod.GET)
	public MsgResult findVocMaxCompentData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'VOCS'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("voc-top-component", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("获取voc组分前十条数据异常", e);
		}
		return result;
	}

	/**
	 * 获取voc臭氧生成潜势前十的数据
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "VOC数据接口", notes = "VOC数据接口获取臭氧生成潜势前十的数据", httpMethod = "GET")
	@SystemLog(moduleName = "VOC数据接口", description = "VOC数据接口获取臭氧生成潜势前十的数据", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "ofp-data", method = RequestMethod.GET)
	public MsgResult findVocMaxOfpData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'VOCS'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("voc-ofp-data", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("获取voc臭氧生成潜势前十的数据异常", e);
		}
		return result;
	}

	/**
	 * 获取voc臭氧生成潜势前十的数据
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "VOC数据接口", notes = "VOC数据接口原始数据查询", httpMethod = "GET")
	@SystemLog(moduleName = "VOC数据接口", description = "VOC数据接口原始数据查询", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "soap-data", method = RequestMethod.GET)
	public MsgResult findVocMaxSoapData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'VOCS'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("voc-soap-data", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("获取voc臭氧生成潜势前十的数据异常", e);
		}
		return result;
	}

	/**
	 * 获取voc的均值统计数据
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "VOC数据接口", notes = "VOC数据接口原始数据查询", httpMethod = "POST")
	@SystemLog(moduleName = "VOC数据接口", description = "VOC数据接口原始数据查询", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "feature-data", method = RequestMethod.POST)
	public MsgResult findVocFeatureData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'VOCS'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("voc-feature-data", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.POST);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("获取voc的均值统计数据异常", e);
		}
		return result;
	}
	
	/**
	 * 获取voc组分均值占比数据
	 *
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "VOC数据接口", notes = "获取voc组分均值占比数据", httpMethod = "POST")
	@SystemLog(moduleName = "VOC数据接口", description = "获取voc组分均值占比数据", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "compont-average", method = RequestMethod.POST)
	public MsgResult findVocCompontAverageData(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'VOCS'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("voc-compont-average", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.POST);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("获取voc组分均值占比数据异常", e);
		}
		return result;
	}
	
	private String getFactors(String[] factors, String catalogCode) {
		JSONArray dicts = new JSONArray();
		JSONObject mapd = new JSONObject();
		for (String string : factors) {
			mapd = new JSONObject();
			mapd.put("dictCode", string);
			mapd.put("catalogCode", catalogCode);
			
			dicts.add(mapd);
		}
		
		Map<String, Object> dictparam = new HashMap<String, Object>();
		dictparam.put("data", dicts);
		List<UnifiedCodePo> results = unifiedcodeService.getCodeInfoList(dictparam);
		
		String afactor = "";
		for (int i = 0; i < results.size(); i++) {
			if (i > 0) {
				afactor += "|";
			}
			afactor += results.get(i).getMyCode();
		}
		
		return afactor;
	}
	
	/**
     * 获取voc相关性分析数据
     *
     * @param request
     * @return
     */
    @RequestMapping(path = "revevance-data", method = RequestMethod.POST)
    public MsgResult findVocRevevanceData(HttpServletRequest request) {
    	Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'VOCS'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			// 转换编码dictcode转为mycode
			if(params.get("airFactors") != null) {
				params.put("airFactors", getFactors(String.valueOf(params.get("airFactors")).split("\\|"), "ITP_AIR"));
			}
			if (params.get("weatherFactors") != null) {
				params.put("weatherFactors", getFactors(String.valueOf(params.get("weatherFactors")).split("\\|"), "ITP_AIR"));
			}
			
			Client c = Client.getInstance();
			String ret = c.execute("voc-revevance-data", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.POST);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("获取voc组分均值占比数据异常", e);
		}
		return result;
	}
    
    /**
     * 获取voc相关性分析数据
     *
     * @param request
     * @return
     */
    @RequestMapping(path = "ofp-average", method = RequestMethod.POST)
    public MsgResult findVocMaxOfpAverageData(HttpServletRequest request) {
    	Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'VOCS'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("voc-ofp-average", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.POST);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("获取voc组分均值占比数据异常", e);
		}
		return result;
	}
    
    /**
     * 获取voc相关性分析数据
     *
     * @param request
     * @return
     */
    @RequestMapping(path = "soap-average", method = RequestMethod.POST)
    public MsgResult findVocMaxSoapAverageData(HttpServletRequest request) {
    	Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'VOCS'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));

			Client c = Client.getInstance();
			String ret = c.execute("voc-soap-average", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.POST);

			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("获取voc组分均值占比数据异常", e);
		}
		return result;
	}
}
